<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Accountrecharge extends CI_Controller {
	
	private $tab ='account';
	
	function __construct(){
		parent::__construct();
		/** 登陆验证 */
		if(!isset($_SESSION)){
		    session_start();
		}
		$admin = $this->session->userdata('admin_user');
		if(!$admin || !isset($admin['user_id'])){
			header('Location: /ychadmin/login');
			exit;
		}
	}
	
	function accountrechargelist(){
		$per_page 	= $this->input->get('per_page')?$this->input->get('per_page'):0;
		$username 	= $this->input->get('username');
		$realname 	= $this->input->get('realname');
		$is_loan 	= isset($_GET['is_loan']) ? $this->input->get('is_loan') : -1;
		$fstatus 	= isset($_GET['fstatus']) ? $this->input->get('fstatus') : -1;
		$ftype		= isset($_GET['ftype']) ? $this->input->get('ftype') : -1;
		$strtime	= $this->input->get('strtime');
		$endtime	= $this->input->get('endtime');
		
		$data = array();
		if($username != ''){
			$data['where']['username'] = $username;
		}
		if($realname != ''){
			$data['where']['realname'] = $realname;
		}
		if($is_loan != '' && $is_loan != -1){
			$data['where']['is_loan'] = $is_loan;
		}
		if($fstatus != '' && $fstatus != -1){
			$data['where']['fstatus'] = $fstatus;
		}
		if($ftype != '' && $ftype != -1){
			$data['where']['ftype'] = $ftype;
		}
		if($strtime != ''){
			$data['where']['strtime'] = $strtime;
		}
		if($endtime != ''){
			$data['where']['endtime'] = $endtime;
		}
		$data['page_size']  = YTZ_LIST_PAGE_SIZE;
		$data['page_start'] = (int)$per_page;
		$this->load->model('Accountrecharge_model');
		$vdata = $this->Accountrecharge_model->get_accountrecharge_list($data);
		$vdata['user_loan'] 			 	= $this->Accountrecharge_model->arrays("user_loan");
		$vdata['account_recharge_status'] 	= $this->Accountrecharge_model->arrays("account_recharge_status");
		$vdata['account_recharge_type'] 	= $this->Accountrecharge_model->arrays("account_recharge_type");
		//分页
		$this->load->library('pagination');
		$config['base_url'] = '/ychadmin/accountrecharge/accountrechargelist/?username='.$username.'&is_loan='.$is_loan.'&fstatus='.$fstatus.'&ftype='.$ftype.'&strtime='.$strtime.'&endtime='.$endtime;
		$config['total_rows'] = $vdata['accountrecharge_count'];
		$config['per_page'] = YTZ_LIST_PAGE_SIZE;
		$this->pagination->initialize($config); 
		
		$this->load->model('Area_model', 'area');
		$vdata['area_list'] = $this->area->get_list();
		$vdata['username'] 	= $username;
		$vdata['realname'] 	= $realname;
		$vdata['is_loan'] 	= $is_loan;
		$vdata['fstatus'] 	= $fstatus;
		$vdata['ftype'] 	= $ftype;
		$vdata['strtime'] 	= $strtime;
		$vdata['endtime'] 	= $endtime;
		
		$vdata['tab'] = $this->tab;
		$vdata['sub'] = 'accountrecharge';
		
		$this->load->view('/ychadmin/accountrecharge_list', $vdata);
	}
	
	function accountrechargeexcel(){
		$username 	= $this->input->get('username');
		$realname 	= $this->input->get('realname');
		$is_loan 	= isset($_GET['is_loan']) ? $this->input->get('is_loan') : -1;
		$fstatus 	= isset($_GET['fstatus']) ? $this->input->get('fstatus') : -1;
		$ftype		= isset($_GET['ftype']) ? $this->input->get('ftype') : -1;
		$strtime	= $this->input->get('strtime');
		$endtime	= $this->input->get('endtime');
		
		$data = array();
		if($username != ''){
			$data['where']['username'] = $username;
		}
		if($realname != ''){
			$data['where']['realname'] = $realname;
		}
		if($is_loan != '' && $is_loan != -1){
			$data['where']['is_loan'] = $is_loan;
		}
		if($fstatus != '' && $fstatus != -1){
			$data['where']['fstatus'] = $fstatus;
		}
		if($ftype != '' && $ftype != -1){
			$data['where']['ftype'] = $ftype;
		}
		if($strtime != ''){
			$data['where']['strtime'] = $strtime;
		}
		if($endtime != ''){
			$data['where']['endtime'] = $endtime;
		}
		$data['limit'] = 'all';
		$data['page_size']  = YTZ_LIST_PAGE_SIZE;
		$data['page_start'] = 0;
		$this->load->model('Accountrecharge_model');
		$vdata = $this->Accountrecharge_model->get_accountrecharge_list($data);
		$var_user_loan 				 = $this->Accountrecharge_model->arrays("user_loan");
		$var_account_recharge_status = $this->Accountrecharge_model->arrays("account_recharge_status");
		$var_account_recharge_type 	 = $this->Accountrecharge_model->arrays("account_recharge_type");
		$this->load->library('PHPExcel');
		$this->load->library('PHPExcel/IOFactory'); 
		$objPHPExcel = new PHPExcel();
		$objPHPExcel->getProperties()->setTitle("用户资金统计")->setDescription(COMPANY_NAME); 
		
		$objPHPExcel->setActiveSheetIndex(0);
		$titles = array("ID", "用户名", "姓名", "用户类型", "订单号", "金额", "手续费","到账", "类型", "备注", 
						"充值时间", "审核时间", "审核备注", "状态");
		
		for($i = 0; $i < count($titles); $i ++){
			$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($i, 1, $titles[$i]);
		}
		$accountrecharge_list = $vdata['accountrecharge_list'];
		for($i = 0; $i < count($accountrecharge_list); $i++){
			$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(0, $i+2, $accountrecharge_list[$i]['id']);
			$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(1, $i+2, $accountrecharge_list[$i]['username']);
			$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(2, $i+2, $accountrecharge_list[$i]['realname']);
			$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(3, $i+2, $var_user_loan[$accountrecharge_list[$i]['is_loan']]);
			$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(4, $i+2, '['.$accountrecharge_list[$i]['trade_no'].']');
			$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(5, $i+2, $accountrecharge_list[$i]['money']);
			$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(6, $i+2, $accountrecharge_list[$i]['fee']);
			$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(7, $i+2, $accountrecharge_list[$i]['money']-$accountrecharge_list[$i]['fee']);
			$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(8, $i+2, $var_account_recharge_type[$accountrecharge_list[$i]['ftype']]);
			$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(9, $i+2, $accountrecharge_list[$i]['remark']);
			$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(10, $i+2, date('Y-m-d H:i:s', $accountrecharge_list[$i]['add_time']));
			$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(11, $i+2, date('Y-m-d H:i:s', $accountrecharge_list[$i]['verify_time']));
			$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(12, $i+2, $accountrecharge_list[$i]['verify_remark']);
			$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(13, $i+2, $var_account_recharge_status[$accountrecharge_list[$i]['fstatus']]);
		}
		
		$objWriter = IOFactory::createWriter($objPHPExcel, 'Excel5'); 
		//发送标题强制用户下载文件 
		header('Content-Type: application/vnd.ms-excel'); 
		header('Content-Disposition: attachment;filename="用户充值.xls"'); 
		header('Cache-Control: max-age=0'); 
		$objWriter->save('php://output'); 
	}
	
	function verify(){
		$admin = $this->session->userdata('admin_user');
		if(!isset($admin['user_id']) || $admin['user_id'] < 1){
			echo "错误";
			exit;
		}
		$id 			= $this->input->post("id");
		$fstatus 		= $this->input->post("fstatus");
		$verify_remark	= $this->input->post("verify_remark");
		$time           = time();
		$ip             = $this->js->get_ip();
		$this->load->model('Accountrecharge_model','recharge');
		$this->load->model('Message_model');
		$rechage_result = $this->recharge->get_one(array("id"=>$id));
//		print_r($rechage_result) ;
		if($fstatus != $rechage_result['fstatus'] && $rechage_result['fstatus']==0){
			$this->db->trans_begin();//事务开始
			$res = array();
			$rec['id'] = $rechage_result['id'];
			$rec['fstatus'] = $fstatus;
			$rec['verify_userid'] = $admin['user_id'];
			$rec['verify_time']   = $time;
			$rec['verify_remark'] = $verify_remark;
			$rec['verify_ip']     = $ip;
	  		$res = $this->recharge->update($id, $rec);
	  		if($res){
	  			$this->load->model('Account_model', 'account');
	  			if($fstatus == 1){
	  				$account_result =  $this->account->get_account($rechage_result['user_id']);	
					$log['user_id'] = $rechage_result['user_id'];
					$log['ftype'] = RECHARGE;
					$log['money'] = $rechage_result['money'];
					//$log['money'] = 0;
					$log['total'] = $account_result['total']+$rechage_result['money'];
					$log['use_money'] = $account_result['use_money']+$rechage_result['money'];
					$log['no_use_money'] = $account_result['no_use_money'];
					$log['collection'] = $account_result['collection'];
					$log['to_user'] = 0;
					$log['add_time'] = $time;
					$log['addip'] = $ip;
					$log['remark'] = $rechage_result['ftype'] == 0 ? "平台充值成功":"充值成功";
					$this->load->model('log_model');
					$this->log_model->add_log('[审核][充值][成功]ID=='.$id);
					$res = $this->account->addlog($log);
					
					if ($res){
						//提醒设置
						$msg = array(
							'sent_user' => '1',
							'receive_user' => $log['user_id'],
							'name' => '充值到账',
							'fstatus' => '0',
							'message_type' => 'system',
							'sented' => '0',
							'deltype' => '0',
							'content' => '您于 '.date('Y-m-d H:i:s').$log['remark'].' 入账：'.$log['money'].' 元',
							'add_time' => $time,
							'addip' => $ip
						);
						$this->Message_model->send($msg);
					}
					
					//2014-03-01取消线下充值奖励
		  			if($rechage_result['ftype'] == 2 && $rechage_result['money'] >= 10000 && $time<strtotime('2014-03-01')){
						$user_account = $this->account->get_account($rechage_result['user_id']);
						
						$topvip = array(//高级VIP名单 =>开始时间  1.5‰线下充值奖励
							'947'=> strtotime('2013-07-01'),
							'1670'=> strtotime('2013-07-01'),
							'1762'=> strtotime('2013-07-01'),
							'2834'=> strtotime('2013-07-01'),
							'2857'=> strtotime('2013-07-01'),
							'2868'=> strtotime('2013-07-01'),
						);
						
						$log['user_id'] 		= $rechage_result['user_id'];
						$log['ftype'] 			= RECHARGE_REWARD;//扣除冻结款
//						$log['money'] 			= isset($topvip[$rechage_result['user_id']]) ? $rechage_result['money']*0.0015 : $rechage_result['money']*CON_CHARGE_AWARD;
                        $log['money'] 			= $rechage_result['money']*0.0015;
						$log['total'] 			= $user_account['total']+$log['money'];
						$log['use_money'] 		= $user_account['use_money']+$log['money'];
						$log['no_use_money'] 	= $user_account['no_use_money'];
						$log['collection'] 		= $user_account['collection'];
						$log['to_user'] 		= 1;
						$log['remark'] 			= "线下充值奖励";
						$log['add_time'] 		= $time;
						$log['addip'] 			= $ip;
						$res = $this->account->addlog($log);
						$this->load->model('log_model');$this->log_model->add_log('[线下充值奖励][充值]');
						
						if ($res){
							$msg2 = array(
								'sent_user' => '1',
								'receive_user' => $log['user_id'],
								'name' => '线下充值奖励',
								'fstatus' => '0',
								'message_type' => 'system',
								'sented' => '0',
								'deltype' => '0',
								'content' => '您于 '.date('Y-m-d H:i:s').$log['remark'].'入账：'.$log['money'].' 元',
								'add_time' => $time,
								'addip' => $ip
							);
							$this->Message_model->send($msg2);
						}
		  			}
	  			}
	  			
	  		}
			if($res){
				$this->db->trans_commit();
				echo '1';
			}else{
				$this->db->trans_rollback();
				$this->load->model('log_model');$this->log_model->add_log('[审核][充值][失败]ID=='.$id);
				echo '失败';
			}
			exit;
		}
	}
	
	
	function recharge_view(){
		$vdata['tab'] = $this->tab;
		$vdata['sub'] = 'recharge';
		$this->load->view('/ychadmin/accountrecharge',$vdata);
	}

	
	function recharge(){
		$ret = array(
			'msg' => '',
			'url' => '',
		);
		$username 		= $this->input->post('username');
		$money 			= $this->input->post('money');
		$remark 		= $this->input->post('remark');
		
		$user_id = 0; 
		if(!$username){
			$ret['msg'] = '请填写用户名';
		}elseif(!$this->myformcheck->IsDouble($money)){
			$ret['msg'] = '请填写有效的金额';
		}elseif(!$remark){
			$ret['msg'] = '请填写备注';
		}else{
			$this->load->model('User_model');
			$user_id = $this->User_model->get_userid_by_username($username);
			if($user_id < 1){
				$ret['msg'] = '用户名不存在';
			}
		}
		if($ret['msg']){
			echo json_encode($ret);exit;
		}
   		
  		$data['user_id'] 	= $user_id;
  		$data['trade_no']	= time().$user_id.rand(1,9);
  		$data['money'] 		= $money;
  		$data['ftype'] 		= 0;
  		$data['remark'] 	= $remark;
  		$data['add_time'] 	= time();
  		$data['addip'] 		= $this->js->get_ip();
  		$this->load->model('Accountrecharge_model');
  		$id = $this->Accountrecharge_model->add($data);
   		if($id > 0){
			$ret['msg'] = '充值成功';
			$this->load->model('log_model');$this->log_model->add_log('[添加][平台充值成功]'.'[用户名:'.$username.',金额:'.$money.']');
		}else{
			$ret['msg'] = '充值失败';
			$this->load->model('log_model');$this->log_model->add_log('[添加][平台充值失败]'.'[用户名:'.$username.',金额:'.$money.']');
		}
   		echo json_encode($ret);
	}
	
	private function received_payments_data($limit=false){
		$this->load->model('Accountrecharge_model');
		$username = $this->input->get('username');
		$is_self 	= isset($_GET['is_self']) ? $this->input->get('is_self') : -1;
		$fstatus 	= isset($_GET['fstatus']) ? $this->input->get('fstatus') : -1;
		$kefu_username = $this->input->get('kefu_username');
		$start_time	= $this->input->get('start_repay_time');
		$end_time	= $this->input->get('end_repay_time');
		
		$start_from =$this->input->get('per_page')?$this->input->get('per_page'):0;
		
		
		if($username != ''){
			$data['where']['username'] = $username;
		}
		
		if($fstatus != '' && $fstatus != -1){
			$data['where']['fstatus'] = $fstatus;
		}
		
		if($is_self != -1){
			$data['where']['is_self'] = $is_self;
		}
		
		if($kefu_username != ''){
			$data['where']['kefu_username'] = $kefu_username;
		}
		
		if($start_time != ''){
			$data['where']['start_repay_time'] = $start_time;
		}
		
		if($end_time != ''){
			$data['where']['end_repay_time'] = $end_time;
		}
		
		$num = YTZ_LIST_PAGE_SIZE;
		$data['page_size']  = intval($num);
		$data['page_start'] = $start_from;
		$data['limit'] = $limit;
		$vdata = $this->Accountrecharge_model->received_payments($data);
		
		$vdata['user_self'] 			 	= $this->Accountrecharge_model->arrays("user_self");
		$vdata['borrow_collection_status'] 			 	= $this->Accountrecharge_model->arrays("borrow_collection_status");
		$vdata['username'] 	= $username;
		$vdata['fstatus'] 	= $fstatus;
		$vdata['is_self'] 	= $is_self;
		$vdata['kefu_username'] 	= $kefu_username;
		$vdata['start_time'] 	= $start_time;
		$vdata['end_time'] 	= $end_time;
		
		$this->load->model('user_model');
		$vdata['kefu_list'] = $this->user_model->get_kefu_list();
		
		return $vdata;
	}
	/**
	 * 
	 * 回款资金列表
	 */
	function received_payments()
	{	
		//获取回款资金列表	
		$vdata = $this->received_payments_data();
		
		//分页
		$this->load->library('pagination');
		$config['base_url'] = '/ychadmin/accountrecharge/received_payments?username='.$vdata['username'].'&fstatus='.$vdata['fstatus'].'&is_self='.$vdata['is_self'].'&kefu_username='.$vdata['kefu_username'].'&start_repay_time='.$vdata['start_time'].'&end_repay_time='.$vdata['end_time'];
		$config['total_rows'] = $vdata['count'];
		$config['per_page'] = YTZ_LIST_PAGE_SIZE;
		$this->pagination->initialize($config); 
		
		$vdata['tab'] = $this->tab;
		$vdata['sub'] = 'received';
		
		$this->load->view('/ychadmin/borrow_payments', $vdata);
	}
	
	
	function received_payments_excel(){
		//获取回款资金列表	
		$vdata = $this->received_payments_data('all');
		
		$this->load->library('PHPExcel');
		$this->load->library('PHPExcel/IOFactory'); 
		$objPHPExcel = new PHPExcel();
		$objPHPExcel->getProperties()->setTitle("回款资金列表")->setDescription(COMPANY_NAME); 
		$objPHPExcel->setActiveSheetIndex(0);
		$titles = array("用户编号", "用户名称", "所属客服", "借款标题", "预还金额", "估计还款时间");
		
		for($i = 0; $i < count($titles); $i ++){
			$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($i, 1, $titles[$i]);
		}
		
		$_list = $vdata['list'];
		
		for($i = 0; $i < count($_list); $i++){
			$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(0, $i+2, $_list[$i]['user_id']);
			$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(1, $i+2, $_list[$i]['username']);
			$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(2, $i+2, $vdata['kefu_list'][$_list[$i]['kefu_userid']]['username']);
			$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(3, $i+2, $_list[$i]['title']);
			$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(4, $i+2, number_format($_list[$i]['money'],2));
			$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(5, $i+2, date('Y-m-d H:i:s', $_list[$i]['repay_time']));
		}
		
		
		header('Content-Type: application/vnd.ms-excel');
		header('Content-Disposition: attachment;filename="回款资金.xls"');
		header('Cache-Control: max-age=0');
		$objWriter = IOFactory::createWriter($objPHPExcel, 'Excel5'); 
		$objWriter->save('php://output');
		exit;
		
	}
}